package com.example.kehoobackend.service.impl;

import com.example.kehoobackend.service.EmailService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;


@Service("emailService")
public class EmailServiceImpl implements EmailService {

    private static final int CODE_LENGTH = 5;

    @Resource
    private JavaMailSender sender;
    @Value("${spring.mail.username}")
    private  String src_email;

    @Autowired
    private RedisTemplate redisTemplate;


    //发送验证码并返回token
    @Override
    public  String sendCode(String email){
        SimpleMailMessage message = new SimpleMailMessage();
        String token = generateToken();
        String code = generateCode();
        //邮件标题
        message.setSubject("【KeHoo】您的验证码");
        //邮件内容
        message.setText("您的验证码是：" + code);
        //谁发送，必须和配置文件中的账号一致
        message.setFrom(src_email);
        //谁接收
        message.setTo(email);
        sender.send(message);


        redisTemplate.opsForValue().set(token,code);
        return token;

    }

    @Override
    public boolean verifyCode(String token, String code) {
        return redisTemplate.opsForValue().get(token).equals(code);
    }

    //生成验证码
    public  String generateCode(){
        Random random = new Random(System.currentTimeMillis());
        String code = String.format("%0" + CODE_LENGTH + "d", random.nextLong(quickPow(10, CODE_LENGTH)));
        return code;
    }

    //生成本次注册的token
    public  String generateToken(){
        return UUID.randomUUID().toString();
    }



    private  long quickPow(long base, int exp){
        if (exp < 0) return -1;
        long res = 1;
        while(exp != 0){
            if ((exp & 1) == 1) res *= base;
            base *= base;
            exp >>= 1;
        }
        return res;
    }





}
